package executors

import scala.actors.Actor
import scala.actors.Actor._
import scala.actors.remote.Node
import scala.actors.remote.RemoteActor._
import org.hibernate.{Session, SessionFactory}
import org.hibernate.cfg.Configuration
import db.User
import db.Client
import db.ClientManager
import db.Folder


/**
 * an object that creates a new client under a received user
 */
object NewClientExecutor/* extends Actor*/{
  
  /**
   * @returns -a string contains userID, clientID, and folderID of the dropbox folder
   */
  def execute(email : String, password : String) : String ={
    val cfg = new Configuration()
    var sessionFactory = null.asInstanceOf[SessionFactory]
    var session = null.asInstanceOf[Session]
    val client = new Client
    var result : Long = 0 
    try{
	    sessionFactory = cfg.configure().buildSessionFactory()
	    session = sessionFactory.openSession()
	    var query = session.createQuery("from User u where u.email = '"+email+"' and u.password = '"+password+"'")
	    val user = query.list.toArray.first.asInstanceOf[User]
	    //creating new client
	    client.setUserID(user.getUserID)
		val clientManager = new ClientManager(session)
		clientManager.saveClient(client)
	    //checking if the user already has a dropbox
	    query = session.createQuery("from Folder f where f.userID = "+user.getUserID+" and f.parent = 0")
	    result = query.list.toArray.first.asInstanceOf[Folder].getFolderID
	    session.flush
    }catch { case (e : Exception)=>{ session.flush; e.printStackTrace }}
    if(!client.getClientID.equals(new java.lang.Long(0)) && !result.equals(new java.lang.Long(0)))
      return (client.getUserID.toString+" "+client.getClientID.toString+" "+result.toString)
    else
      return "Error"
  }
  
/*  def act(){
    
    loop{
      react{
        case(email : String, password : String)=>{
          var dropboxID = execute(email, password)
          sender ! dropboxID
        }
        case "Quit" => exit()
        case _ => println("NewClientActor received unknown message")
      }
    }
  }
*/  
  
  
}
